package com.itshizhan.coroutinedemobasic

import android.os.Bundle
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import kotlinx.coroutines.*


//public fun MainScope(): CoroutineScope = ContextScope(SupervisorJob() + Dispatchers.Main)
class CorotineActivityWithMainScope: AppCompatActivity(), CoroutineScope by MainScope()  {

    lateinit var tv:TextView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        tv = findViewById(R.id.tv)
        launchFromMainScope()
    }

    private fun launchFromMainScope() {
        launch {
            val deferred = async(Dispatchers.IO) {
                // network request
                delay(3000)
                "Get it"
            }
            //tv.text = deferred.await()
            withContext(Dispatchers.Main){
                tv.text = deferred.await()
                Toast.makeText(applicationContext, "MainScope:" + Thread.currentThread().name, Toast.LENGTH_SHORT).show()
            }

        }
    }

}